package com.yc.demo.d0401;

import com.google.gson.Gson;
import com.yc.demo.util.DBHelper;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "HyfcNewsServlet", value = "/HyfcNews.s")
public class HyfcNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Jedis jedis = new Jedis("127.0.0.1",7000);
//        Jedis jedis = new Jedis(); 默认 127.0.0.1 : 6379
//        jedis ~= jdbc 的连接 + 语句对象
        try {
            //判断是否有缓存的新闻
            boolean exists = jedis.exists("hyfc_news");
            List<Map<String,Object>> maps;
            Gson gson = new Gson();
            if(exists){
                //如果有直接返回
                List<String> list = jedis.lrange("hyfc_news", 0, -1);
                maps = new ArrayList<>();
                list.forEach(json ->{
                    HashMap hashMap = gson.fromJson(json, HashMap.class);
                    maps.add(hashMap);
                });
            }else{
                //如果没有则到mysql查询
                String sql = "select * from hyfc_news order by intime desc limit 0,10";
                maps = DBHelper.selectListMap(sql);
                maps.forEach(map ->{
                    String json = gson.toJson(map);
                    //保存到redis中(缓存)
                    jedis.rpush("hyfc_news", json);
                });
            }
            String json = gson.toJson(maps);
            response.getWriter().append(json);
        }finally {
            //关闭jedis 连接
            jedis.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
